<template>
  <div>
    <el-form
      :model="registerForm"
      :rules="rules"
      ref="registerForm"
    >
      <el-form-item prop="username">
        <el-input
          v-model="registerForm.username"
          placeholder="请输入手机号或者邮箱"
        ></el-input>
      </el-form-item>
      <el-form-item
        prop="smscode"
        style="margin-bottom:6px"
      >
        <div class="g-inline">
          <el-input
            placeholder="请输入验证码"
            v-model="registerForm.credential"
            @keyup.enter.native="submitForm('registerForm')"
          ></el-input>
          <el-button
            type="primary"
            style="margin-left: 5px;"
            :loading="codeLoading"
            :disabled="smscode.disabled"
            @click="submitSmsForm('registerForm')"
          >{{smscode.tip}}</el-button>
        </div>
      </el-form-item>
      <el-form-item style="height:20px">
        <el-checkbox v-model="agree"></el-checkbox>
        <span class="agree">
          同意
          <a href="javascript:void(0)">《HiTeam注册协议》</a>&
          <a href="javascript:void(0)">《隐私政策》</a>
        </span>
      </el-form-item>
      <el-form-item>
        <el-button
          class="g-form"
          type="primary"
          :disabled="buttonDisabled"
          :loading="loading"
          @click="submitForm('registerForm')"
        >注册</el-button>
      </el-form-item>
    </el-form>
    <div class="tip">Tip:注册完成后将自动登录</div>
  </div>
</template>

<script>
import {
  MobileRegex,
  EMailRegex
} from '@/utils/regex'
import { mailCodeVerify } from '@/api/auth'
import { smsVerifyCode } from '@/api/notification'
import { mapActions } from 'vuex'
export default {
  name: 'RegisterForm',
  data () {
    return {
      loading: false,
      notify: null,
      agree: false,
      smscode: {
        tip: '发送验证码',
        time: 60,
        timer: null,
        disabled: false
      },
      codeLoading: false,
      registerForm: {
        username: '',
        credential: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入手机号或邮箱', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (!MobileRegex.test(value) && !EMailRegex.test(value)) {
                callback(new Error('手机号或者邮箱格式不正确！'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        credential: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { min: 4, max: 4, message: '长度为4个字符', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    buttonDisabled () {
      return !this.agree
    }
  },
  methods: {
    ...mapActions({
      login: 'user/login'
    }),
    // 提交表单
    submitForm (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (MobileRegex.test(this.registerForm.username)) {
            this.handleSignIn('verification')
          } else if (EMailRegex.test(this.registerForm.username)) {
            this.handleSignIn('email')
          }
        } else {
          return false
        }
      })
    },
    // 提交短信表单
    submitSmsForm (formName) {
      this.$refs[formName].validateField('username', errMsg => {
        if (errMsg) {
        } else {
          if (MobileRegex.test(this.registerForm.username)) {
            this.handleVerifyCode('verification')
          } else if (EMailRegex.test(this.registerForm.username)) {
            this.handleVerifyCode('email')
          }
        }
      })
    },
    // 发送验证码
    async handleVerifyCode (type) {
      console.log(type)
      let response
      switch (type) {
        case 'verification':
          response = await smsVerifyCode(this.registerForm.username)
          this.$notify({ message: response.data, duration: 0 })
          break
        case 'email':
          await mailCodeVerify(this.registerForm.username)
          break
        default:
          return
      }
      this.smscode.tip = this.smscode.time + '秒后重试'
      this.smscode.disabled = true
      this.smscode.timer = setInterval(() => {
        this.smscode.time--
        if (this.smscode.time > 0) {
          this.smscode.tip = this.smscode.time + '秒后重试'
        } else {
          clearInterval(this.smscode.timer)
          this.smscode.disabled = false
          this.smscode.time = 60
          this.smscode.tip = '重新发送'
        }
      }, 1000)
    },
    // 注册
    async handleSignIn (type) {
      const url = '\n<p style="color: #409eff;cursor: pointer;">点击前往设置。</p>'
      this.loading = true
      try {
        // 验证码登录
        const res = await this.login({ userInfo: this.registerForm, type })
        console.log(res)
        this.loading = false
        // 跳转目标
        this.$router.push({ name: 'Home' })
        this.$message.success('注册成功，已自动登录')
        this.notify = this.$notify({
          message: '为了您的账号安全，请前往个人中心设置密码。 ' + url,
          duration: 0,
          dangerouslyUseHTMLString: true,
          onClick: this.onClick
        })
      } catch {
        this.loading = false
      }
    },
    // 通知点击回调
    onClick () {
      this.$router.push({
        path: '/userinfo'
      })
      this.notify.close()
    }
  }
}
</script>

<style lang="scss" scoped>
.inline-ele {
  display: flex;
}
.agree {
  font-size: 14px;
  color: #9199a1;
}
.tip {
  font-size: 14px;
  text-align: center;
  color: #999;
}
</style>
